package com.epfresh.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.View;

import com.epfresh.R;
import com.epfresh.adapter.DeliveryCenterItemViewBinder;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestEntityPurchase;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.bean.DeliveryCenterListEntity;
import com.epfresh.global.BaseActivity;
import com.epfresh.views.CustomAlertDialog;
import com.epfresh.views.MultiStateView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import multitype.MultiTypeAdapter;

public class MoreDeliveryCenterActivity extends BaseActivity {
    private MultiTypeAdapter multiAdapter;
    private List<Object> items = new ArrayList<>();
    private PtrFrameLayout ptrFrameLayout;
    private RecyclerView rv_delivery_center;

    private MultiStateView multi_state;
    private boolean isRefresh = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_more_delivery_center);

        initView();
        reqDeliveryCenterList();
    }

    private void initView() {
        toolbarTitle.setText("配送中心");

        multi_state = findViewById(R.id.multi_state);
        multi_state.setViewForState(R.layout.loading_view, MultiStateView.VIEW_STATE_LOADING);

        multiAdapter = new MultiTypeAdapter();
        ptrFrameLayout = findViewById(R.id.ptr_md_frame);
        rv_delivery_center = findViewById(R.id.rv_delivery_center);

        ptrFrameLayout.setPtrHandler(ptrHandler);

        DeliveryCenterItemViewBinder itemViewBinder = new DeliveryCenterItemViewBinder();
        itemViewBinder.setOnItemClickListener(new DeliveryCenterItemViewBinder.OnItemClickListener() {
            @Override
            public void onItemClick(DeliveryCenterListEntity.StoreListBean item) {
                Intent tv_bulk_load = new Intent(MoreDeliveryCenterActivity.this, DcStoreActivity.class);//跳转到配送中心详情
                tv_bulk_load.putExtra("storeId", item.getStoreId());
                startActivity(tv_bulk_load);
            }

            @Override
            public void onApplyVIP(DeliveryCenterListEntity.StoreListBean item) {
                showAlertDialog(item.getStoreName(), item.getStoreId());
            }
        });
        multiAdapter.register(DeliveryCenterListEntity.StoreListBean.class, itemViewBinder);

        multiAdapter.setItems(items);
        rv_delivery_center.setLayoutManager(new LinearLayoutManager(this));
        rv_delivery_center.setAdapter(multiAdapter);
    }


    private void showAlertDialog(String strStoreName, final String storeId) {
        final CustomAlertDialog alertDialog = new CustomAlertDialog(this);
        alertDialog.setTitles(Html.fromHtml("您正在向<font color=\"#24AF75\">“" + strStoreName + "”</font>申请会员"))
                .setTitleColor("#313131")
                .setMessage("申请通过后可享受商户服务")
                .setMessageColor("#666666")
                .setNoVis(true)
                .setCancelOnTouchOutside(true)
                .setYesOnClickListener("确认", new CustomAlertDialog.YesOnClickListener() {
                    @Override
                    public void yesClick() {
                        applyVIP(storeId);
                        alertDialog.dismiss();
                    }
                })
                .setNoOnClickListener("取消", new CustomAlertDialog.NoOnClickListener() {
                    @Override
                    public void noClick() {
                        alertDialog.dismiss();
                    }
                })
                .show();
    }


    /**
     * 刷新
     */
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rv_delivery_center, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    private void refresh() {
        items.clear();
        isRefresh = true;
        reqDeliveryCenterList();
    }


    /**
     * 请求配送中心列表
     */
    private void reqDeliveryCenterList() {
        RequestEntityMap requestEntity = new RequestEntityMap();
        requestEntity.setCmd(AppPurchaseRouterConstant.cmd_delivery_center_list);
        requestEntity.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
        requestEntity.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());

        request(requestEntity, AppPurchaseRouterConstant.cmd_delivery_center_list, new OnRequestListener<List<DeliveryCenterListEntity>>() {
            @Override
            public List<DeliveryCenterListEntity> jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, new TypeToken<List<DeliveryCenterListEntity>>() {
                }.getType());
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                T.toast(failCode + "");
                ptrFrameLayout.refreshComplete();
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                T.toast(failCode + "");
                ptrFrameLayout.refreshComplete();
            }

            @Override
            public void onStart(Object tag) {
                if (!isRefresh) {
                    multi_state.setViewState(MultiStateView.VIEW_STATE_LOADING);
                }
            }

            @Override
            public void onResponse(ResponseEntity<List<DeliveryCenterListEntity>> response, Object tag) {
                ptrFrameLayout.refreshComplete();
                multi_state.setViewState(MultiStateView.VIEW_STATE_CONTENT);

                List<DeliveryCenterListEntity> deliveryCenterListEntities = response.getResponseElement();

                if (deliveryCenterListEntities != null && deliveryCenterListEntities.size() > 0) {
                    for (int j = 0; j < deliveryCenterListEntities.size(); j++) {
                        for (int i = 0; i < deliveryCenterListEntities.get(j).getStoreList().size(); i++) {
                            deliveryCenterListEntities.get(j).getStoreList().get(i).setMerchantName(deliveryCenterListEntities.get(j).getMarketName());
                            if (i == 0) {
                                deliveryCenterListEntities.get(j).getStoreList().get(i).setMarketName(deliveryCenterListEntities.get(j).getMarketName());
                            }
                            if (j == deliveryCenterListEntities.size() - 1 && i == deliveryCenterListEntities.get(j).getStoreList().size() - 1) {
                                deliveryCenterListEntities.get(j).getStoreList().get(i).setEnd(true);
                            }
                        }
                    }

                    for (DeliveryCenterListEntity deliveryCenterListEntity : deliveryCenterListEntities) {
                        items.addAll(deliveryCenterListEntity.getStoreList());
                    }
                }

                multiAdapter.notifyDataSetChanged();
            }
        });

    }

    /**
     * 申请会员
     *
     * @param storeId
     */
    private void applyVIP(String storeId) {
        RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
        data.setCmd(AppPurchaseRouterConstant.cmd_store_store_bind);
        Map<String, String> map = new HashMap<>();
        map.put("storeId", storeId);
        data.setParameters(map);

        request(data, AppPurchaseRouterConstant.cmd_store_store_bind, new OnRequestListener<StatusEntity>() {
            @Override
            public StatusEntity jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, StatusEntity.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                hideProgressDialog();
                T.toast(failCode + "");
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                hideProgressDialog();
                T.toast(failCode + "");
            }

            @Override
            public void onStart(Object tag) {
                showProgressDialog();
            }

            @Override
            public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
                hideProgressDialog();
                StatusEntity responseElement = response.getResponseElement();
                if (responseElement.isSuccess()) {
                    refresh();
                } else {
                    T.toast("申请失败");
                }
            }
        });
    }
}
